import { isRef } from 'vue'

/**
 * @description 从localStorage中获取对应key的value
 * @param key:string 查找的key
 * @return 返回key对应的value
 */
function getLocalStorage(key: string): any {
	return localStorage.getItem(key) ? localStorage.getItem(key) : false
}

/**
 * @description 将key和对应的value存入本地localStorage中
 * @param key:string 需要存入的key
 * @param value:any key对应的value
 */
function setLocalStorage(key: string, value: any) {
	localStorage.setItem(key, value)
}

/**
 * @description 从localStorage中移除指定key的值
 * @param key:string 需要删除的key
 */
function removeLocalStorage(key: string) {
	if (!getLocalStorage(key)) {
		console.error('localstorage does not have this key')
		return
	}
	localStorage.removeItem(key)
}

/**
 *  @description 通过正则简化当前将当前天气归类，并简化
 *  @param weather:string 根据api返回的当前天气简略
 *  @return 返回概括的天气
 * */
function getWeatherType(weather: string): string {
	let regArr = [
		['sunny', /^晴$/g],
		['dark', /^阴$/g],
		['cloudy', /.?云.?/g],
		['windy', /.?风.?/g],
		['smog', /.?霾.?/g],
		['rainy', /.?雨.?/g],
		['snow', /.?雪.?/g],
		['sand', /.?[尘沙].?/g],
		['fog', /.?雾.?/g],
		['hot', /^热$/g],
		['cold', /^冷$/g],
		['Foshan', /^未知$/g],
	]
	let regMap = new Map()
	let result: string = ''
	regArr.forEach(([key, value]) => {
		regMap.set(key, value)
	})
	for (const [key, value] of regArr) {
		if (weather.match(value)) {
			result = key as string
		}
	}
	return result
}

/**
 * @description 遍历对象数组或对象，找出拥有指定dataKey和data的对象或对象所在的下标（下标只能显示最外层）
 *  @param dataKey:string 搜索的key
 *  @param data:any dataKey对应的数据
 *  @param target:any 要遍历的目标对象或数组
 *  @return 返回结果对象
 * */
let result: any = false

function getValInObj(dataKey: string, data: any, target: any) {
	result = false
	const setResult = (dataKey: string, data: any, target: any) => {
		if (target.length || Object.keys(target).length) {
			for (let key in target) {
				if (Object.hasOwn(target, key)) {
					let element = target[key]
					if (element instanceof Object) {
						setResult(dataKey, data, element)
					} else {
						if (element === data) {
							result = target
							break
						}
					}
				}
			}
		}
	}
	if (isRef(target)) setResult(dataKey, data, target.value)
	else setResult(dataKey, data, target)

	return result
}

/**
 * @description 返回六位随机数
 */
function getRandomId() {
	return Math.floor(Math.random() * 1000000)
}

export {
	getRandomId,
	getLocalStorage,
	setLocalStorage,
	removeLocalStorage,
	getWeatherType,
	getValInObj,
}
